//
//  OrderRealtimeDataViewController.m
//  OMS
//
//  Created by goldeney on 14/10/22.
//  Copyright (c) 2014年 ShangHai Goldeneye Techonology Co.,Ltd. All rights reserved.
//

#import "OMOrderRealtimeDataViewController.h"
#import "NSKeyedArchiverUserLogin.h"
#import "NSDictionary+DataFormat.h"

#import "UITableView+Custom.h"
#import "WebServiceCommonRequest.h"
#import "MJRefresh.h"
#import "OMOrderRealtimeDataViewCell.h"

@interface OMOrderRealtimeDataViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate>

@property (strong, nonatomic) UISearchDisplayController *searchDisplayController;
@property (strong, nonatomic) UITableView *tableView;

@property (strong, nonatomic) NSMutableArray *contentListData;
@property (strong, nonatomic) NSMutableArray *searchListData;

@end

@implementation OMOrderRealtimeDataViewController
@synthesize tableView = _tableView;
@synthesize searchDisplayController;

-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"请选择合同";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.contentListData = [NSMutableArray array];
    self.searchListData = [NSMutableArray array];
    [self addUISearchBar];
    
    CGFloat searchBarHeight = searchDisplayController.searchBar.frame.size.height;
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, searchBarHeight, SuperWidth, SuperHeight - searchBarHeight)];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.tableView.autoresizesSubviews = YES;
    [self.view addSubview:_tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left);
        make.right.mas_equalTo(self.view.mas_right);
        make.top.mas_equalTo(self.searchDisplayController.searchBar.mas_bottom);
        make.bottom.mas_equalTo(self.view.mas_bottom);
    }];
    
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 60;
    
    //获取合同数据
    [self setupRefresh];
}

//添加搜索框
- (void)addUISearchBar
{
    UISearchBar *searchbar=[[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 44)];
    searchbar.placeholder = @"合同搜索";
    searchbar.autocorrectionType = UITextAutocorrectionTypeNo;
    searchbar.autocapitalizationType = UITextAutocapitalizationTypeNone;
    searchbar.delegate = self;//设置代理
    searchbar.backgroundColor = [UIColor colorWithRed:230/255.00 green:230/255.00 blue:230/255.00 alpha:0.80];
    for (UIView *view in searchbar.subviews) {
        // for before iOS7.0
        if ([view isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
            [view removeFromSuperview];
            break;
        }
        // for later iOS7.0(include)
        if ([view isKindOfClass:NSClassFromString(@"UIView")] && view.subviews.count > 0) {
            [[view.subviews objectAtIndex:0] removeFromSuperview];
            break;
        }
    }
    
    searchDisplayController = [[UISearchDisplayController alloc]initWithSearchBar:searchbar contentsController:self];
    searchDisplayController.active = NO;
    searchDisplayController.searchResultsDataSource = self;
    searchDisplayController.searchResultsDelegate = self;
    searchDisplayController.searchResultsTableView.tableFooterView = [[UIView alloc] init];
    
    searchDisplayController.searchResultsTableView.rowHeight = UITableViewAutomaticDimension;
    searchDisplayController.searchResultsTableView.estimatedRowHeight = 60;
    
    //self.tableView.tableHeaderView = searchbar;
    [self.view addSubview:searchbar];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setupRefresh
{
    //添加下拉加载数据
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    [self.tableView headerBeginRefreshing];
    [self.tableView footerEndRefreshing];
}

- (void)stopRefresh
{
    //移除下拉加载数据
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
}

#pragma mark UISearchBarDelegate

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText;
{
    [searchDisplayController.searchResultsTableView reloadData];
    [self getSearchNetWorkDataText:searchText];
}

- (void)getSearchNetWorkDataText:(NSString*)searchText
{
    //@状态（全部、供毕、正供、待供）
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"HTGL_HTLB_LIST_20170117"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    [content addParameterKey:@"起始条数" value:@0];
    [content addParameterKey:@"结束条数" value:@100];
    [content addParameterKey:@"合同性质" value:@""];
    [content addParameterKey:@"审核状态" value:@""];
    [content addParameterKey:@"合同状态" value:@""];
    [content addParameterKey:@"分发状态" value:@""];
    [content addParameterKey:@"客户编号" value:@""];
    [content addParameterKey:@"检索条件" value:searchText];
    [content addParameterKey:@"合同ID" value:@""];
    
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    [content addParameterKey:@"用户ID" value:userInfo.Id];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        [self.searchListData removeAllObjects];
        if(firstArray && firstArray.count>0){
            [self.searchListData addObjectsFromArray:firstArray];
            [searchDisplayController.searchResultsTableView reloadData];
        } else{
            searchDisplayController.searchResultsTitle = @"未找到合同";
            [searchDisplayController.searchResultsTableView reloadData];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        searchDisplayController.searchResultsTitle = @"哦，出错了";
        [searchDisplayController.searchResultsTableView reloadData];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        searchDisplayController.searchResultsTitle = @"无法连接网络";
        [searchDisplayController.searchResultsTableView reloadData];
    }];
    
}

#pragma mark 网络获取数据

- (void)getNetWorkDataIsReresh:(BOOL)isReresh state:(NSNumber*)state end:(NSNumber*)end
{
    //@状态（全部、供毕、正供、待供）
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"HTGL_HTLB_LIST_20170117"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    [content addParameterKey:@"起始条数" value:state];
    [content addParameterKey:@"结束条数" value:end];
    [content addParameterKey:@"合同性质" value:@""];
    [content addParameterKey:@"审核状态" value:@""];
    [content addParameterKey:@"合同状态" value:@""];
    [content addParameterKey:@"分发状态" value:@""];
    [content addParameterKey:@"客户编号" value:@""];
    [content addParameterKey:@"检索条件" value:@""];
    [content addParameterKey:@"合同ID" value:@""];
    
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    [content addParameterKey:@"用户ID" value:userInfo.Id];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        if(isReresh) [self.tableView headerEndRefreshing];
        else [self.tableView footerEndRefreshing];
        
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        if(isReresh) [self.contentListData removeAllObjects];
        if(firstArray && firstArray.count>0){
            [self.contentListData addObjectsFromArray:firstArray];
            [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
            [self.tableView reloadData];
        } else if(isReresh){
            [self.tableView setTableViewNotDataDrawText:@"暂无有效合同" isShow:YES];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        if(isReresh)[self errorInfoViewText:@"哦，出错了"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        if(isReresh)[self errorInfoViewText:@"无法连接网络"];
    }];
    
}

- (void)errorInfoViewText:(NSString*)label
{
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
    
    if (self.tableView.visibleCells.count <= 0) {
        [self.tableView setTableViewNotDataDrawText:label isShow:YES];
    } else {
        [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
        [self showErrorHUDText:label];
    }
}

#pragma mark 开始进入刷新状态

- (void)headerRereshing
{
    NSNumber *stateNumber = [NSNumber numberWithInteger:0];
    NSNumber *endNumber = [NSNumber numberWithInteger:20];
    [self getNetWorkDataIsReresh:YES state:stateNumber end:endNumber];
}

- (void)footerRereshing
{
    NSNumber *stateNumber = [NSNumber numberWithInteger:self.contentListData.count];
    NSNumber *endNumber = [NSNumber numberWithInteger:self.contentListData.count + 20];
    [self getNetWorkDataIsReresh:NO state:stateNumber end:endNumber];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == searchDisplayController.searchResultsTableView) {
        return self.searchListData.count;
    } else {
        return self.contentListData.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *mCellWithIdentifier = @"OMOrderRealtimeDataViewCell";
    OMOrderRealtimeDataViewCell *cell = [tableView dequeueReusableCellWithIdentifier:mCellWithIdentifier];
    if (!cell) {
        cell = [[OMOrderRealtimeDataViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:mCellWithIdentifier];
    }
    
    NSDictionary *dictionary = nil;
    if (tableView == searchDisplayController.searchResultsTableView){
        dictionary = [self.searchListData objectAtIndex:indexPath.row];
    } else {
        dictionary = [self.contentListData objectAtIndex:indexPath.row];
    }
    
    //是否可以被选择
    if([dictionary objectFormatIntegerForKey:@"SFDDKY"] <= 0){
        cell.userInteractionEnabled = NO;
        cell.backgroundColor = ThemeColorBackgroundGary;
        cell.HTBZLabel.textColor = ThemeColorBlue;
    } else {
        cell.userInteractionEnabled = YES;
        cell.backgroundColor = [UIColor whiteColor];
        cell.HTBZLabel.textColor = [UIColor darkGrayColor];
    }
    
    cell.HTBHLabel.text = [dictionary objectFormatStringForKey:@"合同编号" defaults:@"无合同编号"];
    cell.HTMCLabel.text = [dictionary objectFormatStringForKey:@"合同名称" defaults:@"无合同名称"];
    cell.SGDWLabel.text = [dictionary objectFormatStringForKey:@"施工单位" defaults:@"无施工单位"];
    cell.HTBZLabel.text = [dictionary objectFormatStringForKey:@"报废备注" defaults:@"无"];
    cell.SYFLLabel.text = [dictionary objectFormatFloatStringForKey:@"剩余签订量" retain:1 except:10000 exceptFormat:@"剩%@万方" format:@"剩%@方"];
    
    return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *dictionary = nil;
    if (tableView == searchDisplayController.searchResultsTableView){
        dictionary = [self.searchListData objectAtIndex:indexPath.row];
    } else {
        dictionary = [self.contentListData objectAtIndex:indexPath.row];
    }
    
    //网络获取工程数据
    [self getNetWorkDataBackContractInfo:dictionary];
}

#pragma mark 网络获取工程数据

- (void)getNetWorkDataBackContractInfo:(NSDictionary*)concreteInfo
{
    //@状态（全部、供毕、正供、待供）
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"HTGL_GCMC_LIST"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    NSString *concreteID = [concreteInfo objectFormatStringForKey:@"合同ID"];
    [content addParameterKey:@"合同ID" value:concreteID];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        if(firstArray && firstArray.count>0){
            //关闭页面，返回数据
            NSArray *array = @[concreteInfo, firstArray];
            if (self.backResultDelagate && [self.backResultDelagate respondsToSelector:@selector(backResultDataKey:dataValue:)]) {
                [self.backResultDelagate backResultDataKey:self.key dataValue:array];
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        } else{
            [self showAlertView:@"该合同无工程，请选择其它合同"];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self showAlertView:@"系统繁忙，请稍后再试"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self showAlertView:@"请检查网络是否正常"];
    }];
    
}

#pragma mark - UIAlertView

- (void)showAlertView:(NSString*)message
{
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    alert.alertViewStyle=UIAlertViewStyleDefault;
    [alert show];
}

#pragma mark -
#pragma mark backButtonEvent

- (void)backButtonEvent:(id)sender
{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

@end
